<template>
  <div class="tag">
    <div class="left">
      <el-tag
        :class="act(tag.name) ? 'active' : ''"
        :key="index"
        v-for="(tag, index) in dynamicTags"
        closable
        @click="change(index, tag)"
        :disable-transitions="false"
        @close="handleClose(index, tag)"
      >
        {{ tag.title }}
      </el-tag>
    </div>
    <div class="right">
      <el-dropdown @command="handleCommand" size="small">
        <el-button type="primary" size="mini">
          更多菜单<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="now">关闭其他</el-dropdown-item>
          <el-dropdown-item divided command="all">关闭所有</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
  </div>
</template>

<script>
import bus from "../bus/bus";
export default {
  // 标签组件的思路

  // 1: 创建标签    监听路由（当路由发生改变的时候push到新数组中,要保持数组中唯一性,）
  // 2：当前选中标签     创建选中色，当每一项路由和当前路由相等时，设为true
  // 3：关闭标签时  当标签数组长度大于0时，进入if=>当前路由和点击关闭标签路由相等时，再次进入if两种情况（1：当前点击关闭标签的下标index>0时，push到前一个路由，else push到当前标签组下标index中）
  //               else push到首页
  data() {
    return {
      dynamicTags: [],
      isFalag: false,
    };
  },
  watch: {
    $route: {
      handler(newValue, oldValue) {
        this.setTags(newValue);
      },
      immediate: true,
    },
  },
  mounted() {
    // if(this.dynamicTags.length===0 && this.$route.name==='home_page1'){
    //   this.dynamicTags.push({name:'home_page1',title:'系统首页'})
    // }
    // // debugger;
    //  window.addEventListener("beforeunload", e =>{
    //       localStorage.setItem('tagList',JSON.stringify([{name:this.$route.name,title:this.$route.meta.title}]))
    //   })
    // this.dynamicTags=JSON.parse(localStorage.getItem('tagList'))
  },
  methods: {
    setTags(val) {
      var flag;
      if (this.dynamicTags || this.dynamicTags === null) {
        flag = this.dynamicTags.some((item) => {
          return item.name === val.name;
        });
      }
      if (this.dynamicTags.length > 5 && !flag) {
        this.dynamicTags.shift();
      }
      if (!flag) {
        var obj = {
          title: val.meta.title,
          name: val.name,
        };
        this.dynamicTags.push(obj);
      }
      this.keep_alive();
    },
    handleClose(index, row) {
      const str = this.dynamicTags;
      str.splice(index, 1);
      if (str.length > 0) {
        if (this.$route.name === row.name) {
          index > 0
            ? this.$router.push({ name: str[index - 1].name })
            : this.$router.push({ name: str[index].name });
        }
      } else {
        this.$router.push("/");
      }
      this.keep_alive();
    },
    change(index, row) {
      this.$router.push({ name: row.name });
    },
    act(val) {
      return val === this.$route.name;
    },
    handleCommand(val) {
      var array = [];
      if (val === "now") {
        for (var i = 0; i < this.dynamicTags.length; i++) {
          if (this.dynamicTags[i].name === this.$route.name) {
            array.push(this.dynamicTags[i]);
          }
        }
        this.dynamicTags = array;
      } else if (val === "all") {
        this.dynamicTags = [];
        this.$router.push({ name: "home_page1" });
      }
      this.keep_alive();
    },
    keep_alive() {
      let arr = [];
      this.dynamicTags.map((item) => {
        if (item.name) {
          return arr.push(item.name);
        }
      });
      bus.$emit("dynamicTags",arr);
    },
  },
};
</script>

<style scoped>
.tag {
  padding: 10px 10px 10px 10px;
  background: #fff;
  box-sizing: border-box;
  display: flex;
}
.el-tag {
  margin: 0 5px;
  cursor: pointer;
}
.active {
  background: green;
}
.left {
  flex: 1;
}
.right {
  display: flex;
  flex-basis: 200px;
  justify-content: flex-end;
}
</style>